<template>
  <!-- 教师职务设置 -->
  <div>
    <!-- 表单-->
    <el-form :model="form" label-position="right" label-width="100px">
      <!-- 职务-->
      <el-form-item label="职务">
        <!-- 职务选择框-->
        <el-select v-model="form.appointment_ids" multiple collapse-tags>
          <el-option
            v-for="item in appointments"
            :key="item.appointment_id"
            :label="item.appointment_name"
            :value="item.appointment_id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import service from "@/utils/service";

export default {
  data() {
    return {
      form: {
        appointment_ids: [],//教师所选择的所有职务的id所组成的数组
      },
      //职务表中所有职务，用来渲染职务选择列表项
      appointments: [],
    };
  },
  methods: {
    //获取职务表中所有职务
    async getAllAppointmens() {
      try {
        const apiUrl = "/teachers/appointment";
        const response = await service.get(apiUrl);
        if (response.data.code === 20041) {
          this.appointments = response.data.data;
        }
      } catch {
        console.log("获取所有职务出错");
      }
    },
    //根据教师登录后的token获取当前教师的职务信息
    async getCurrentTeacherAppointments() {
      try {
        const apiUrl =
          "/teachers/getCurrentTeacherAppointment";
        const response = await service.get(apiUrl, {
          headers: {
            Authorization: this.$store.state.token,
          },
        });

        if (response.data.code === 20041) {
          this.form.appointment_ids = response.data.data;
        }
      } catch {
        console.log("获取当前教师职务信息出错");
      }
    },
    //保存按钮对应的方法，提交修改职务的请求
    async handleSave() {
      try {
        const apiUrl =
          "/teachers/updateCurrentTeacherAppointment";
        const response = await service.put(apiUrl, this.form.appointment_ids, {
          headers: {
            Authorization: this.$store.state.token,
          },
        });

        if (response.data.code === 20031) {
          this.$message.success("保存成功");
        } else {
          this.$message.error('修改出错，请重试');
        }

      } catch {
        console.log("当前教师修改职务出错");
      }
    },

  },
  created() {
    this.getAllAppointmens();
    this.getCurrentTeacherAppointments();
  },
};
</script>

<style>
</style>
